﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;


namespace CCPSIP.Sticker
{
    /// <summary>CCPSIP_029：接收禮物貼圖 API</summary>
    /// idHeader = 裝置 UUID 前八碼。
    /// checkcode = 裝置限時驗證碼。
    /// Sender = 送禮人的帳號。
    /// StickerID = 貼圖ID，目前為資料夾名稱。
    /// ConfirmAct = 接受="Y"，拒絕="N"。

    public class gift_confirm : IHttpHandler
    {
        private const string kStickerRootDir = @"\\192.168.19.1\iSender_D";
        private const string kWinUserId = "ccpsip_cloud";
        private static byte[] kWinUserKey = { 0x59, 0x4C, 0x43, 0x71, 0x6A,
                                          0x6D, 0x44, 0x6A, 0x32, 0x5A,
                                          0x72, 0x62, 0x72, 0x43, 0x39,
                                          0x68, 0x51, 0x6E, 0x63, 0x6B,
                                          0x57, 0x32, 0x64, 0x74, 0x62
                                        };
        private const string kGiftRootDir = @"\\192.168.19.1\iSender_D\Gift";


        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";


            try
            {
                //【01】取得POST參數，驗證身分
                //
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];
                string Sender = req.Form["Sender"];//送禮人的帳號
                string StickerID = req.Form["StickerID"];//貼圖ID，目前為資料夾名稱
                bool Accepted = (req.Form["ConfirmAct"].ToUpper() == "Y" ? true : false);//接受或拒絕

                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                {
                    throw new Exception("Error_01: Cannot identify this device");//無法識別此裝置
                }

                string Recipient = userInfo.SIP_Num;


                //【02】檢查是否有送禮記錄
                //
                bool hasGift = OracleKitSticker.hasGift(Sender, Recipient, StickerID);
                if (!hasGift)
                {
                    throw new Exception("Error_02: Gift not found");//找不到禮物
                }


                //【03】更改送禮記錄狀態
                //
                OracleKitSticker.ConfirmGift(Sender, Recipient, StickerID, Accepted);


                //【04】組合路徑
                //
                string srcParent1 = string.Format(@"{0}\{1}", kGiftRootDir, Recipient);
                string srcParent2 = string.Format(@"{0}\{1}", srcParent1, Sender);
                string sourceDir = string.Format(@"{0}\{1}", srcParent2, StickerID);

                string userDirName = Recipient;
                if (SipKit.isHQMobileExt(Recipient))
                {
                    userDirName = SipKit.getHQDesktopExt(Recipient);
                }
                string targetDir = string.Format(@"{0}\{1}\Stickers\{2}", kStickerRootDir, userDirName, StickerID);


                //【05】切換網域身分存取資料夾
                //
                string tempCode = System.Text.Encoding.UTF8.GetString(kWinUserKey);

                using (new Tools.Impersonator(kWinUserId, "", tempCode))
                {
                    if (Accepted)
                    {
                        //【06】接受禮物
                        //
                        if (!Directory.Exists(sourceDir))
                        {
                            throw new Exception("Error_03: Sticker not found");//貼圖不存在
                        }

                        //【06-1】刪除同名稱的舊貼圖
                        //
                        if (Directory.Exists(targetDir))
                        {
                            Directory.Delete(targetDir, true);
                        }
                        else
                        {
                            string ParentDir = Directory.GetParent(targetDir).FullName;
                            if (!Directory.Exists(ParentDir))
                                Directory.CreateDirectory(ParentDir);
                        }

                        //【06-2】把禮物貼圖移動到自己的貼圖區
                        //
                        Directory.Move(sourceDir, targetDir);
                    }
                    else
                    {
                        //【07】拒絕禮物
                        //
                        if (Directory.Exists(sourceDir))
                        {
                            Directory.Delete(sourceDir, true);
                        }
                    }


                    //【08】清理空資料夾
                    //
                    if (Directory.GetDirectories(srcParent2).Length == 0)
                    {
                        Directory.Delete(srcParent2, false);
                    }
                    if (Directory.GetDirectories(srcParent1).Length == 0)
                    {
                        Directory.Delete(srcParent1, false);
                    }
                }//End of Impersonator


                //【99】回傳OK
                //
                resultStr = "OK";
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
